<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
?>
<SCRIPT type="text/javascript" src="/view/javascripts/form.js"></SCRIPT>
<DIV class="block">
	<H1>Структурные подразделения</H1>
	<TABLE>
		<TR>
			<TH>название</TH>
			<TH>тип</TH>
			<TH>руководитель</TH>
		</TR>
<?php
$size = count($response->getParameter('departments')) - 1;
foreach($response->getParameter('departments') as $i => $department) {
	showDepartment($department, $i == $size);
}
?>
	</TABLE>
</DIV>
<DIV class="block">
	<FORM action="/department/edit.html" method="post">
		<BUTTON type="submit">
			<IMG src="/view/img/button-new.png" alt="">
			<SPAN>новое</SPAN>
		</BUTTON>
	</FORM>
</DIV>

<?php
function showDepartment(Department $department, $isLast = false, $levels = null) {
	$id = $department->getIdentity();
	$name = $department->getName();
	$type = $department->getType()->getName();
	if($department->getHead() !== null) {
		$head = $department->getHead()->getPerson()->getFullName();
	} else {
		$head = '&nbsp;';
	}
	$editId = 'edit-'.$id;
?>
<TR onclick="submitForm('<?php echo $editId;?>')">
	<TD>
		<FORM action="/department/edit.html" method="post"
				id="<?php echo $editId;?>">
		<INPUT type="hidden" name="identity" value="<?php echo $id;?>">
		</FORM>
<?php
	if($levels !== null) {
		foreach($levels as $level) {
			if($level) {
?>
		<DIV class="image-1"></DIV>
<?php
			} else {
?>
		<DIV class="image-0"></DIV>
<?php
			}
		}
		$levels[] = !$isLast;
	} else {
		$levels = array();
	}
	if(count($levels) > 0) {
		if($isLast) {
?>
		<DIV class="image-3"></DIV>
<?php
		} else {
?>
		<DIV class="image-2"></DIV>
<?php
		}
	}
	echo $name;
?>
	</TD>
	<TD><?php echo $type;?></TD>
	<TD><?php echo $head;?></TD>
</TR>
<?php
	$n = count($department->getChildren()) - 1;
	foreach($department->getChildren() as $i => $child) {
		showDepartment($child, $i == $n, $levels);
	}
}
?>